<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminOrderController extends Controller
{
    use LogsActivity;
    /**
     * 显示订单列表
     */
    public function index(Request $request)
    {
        $query = Order::with([
                'user',
                'items.product.images',
                'items.variant.images',
                'payments' => function($query) {
                    $query->orderBy('created_at', 'desc');
                }
            ])
            ->orderBy('created_at', 'desc');

        // 订单状态筛选
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // 支付状态筛选
        if ($request->filled('payment_status')) {
            $query->where('payment_status', $request->payment_status);
        }

        // 搜索（订单号、收货人、手机号）
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhere('receiver_name', 'like', "%{$search}%")
                  ->orWhere('receiver_phone', 'like', "%{$search}%");
            });
        }

        // 日期范围筛选
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        // 金额区间筛选
        if ($request->filled('amount_min')) {
            $query->where('total_amount', '>=', $request->amount_min);
        }
        if ($request->filled('amount_max')) {
            $query->where('total_amount', '<=', $request->amount_max);
        }

        $orders = $query->paginate(20);

        // 订单统计
        $stats = [
            'total_orders' => Order::count(),
            'pending_orders' => Order::where('status', 'pending')->count(),
            'processing_orders' => Order::where('status', 'processing')->count(),
            'shipped_orders' => Order::where('status', 'shipped')->count(),
            'delivered_orders' => Order::where('status', 'delivered')->count(),
            'cancelled_orders' => Order::where('status', 'cancelled')->count(),
            'total_amount' => Order::sum('total_amount'),
            'paid_amount' => Order::where('payment_status', 'paid')->sum('total_amount'),
            'pending_amount' => Order::where('payment_status', 'pending')->sum('total_amount'),
        ];

        return Inertia::render('Admin/Orders/Index', [
            'orders' => $orders,
            'stats' => $stats,
            'filters' => $request->only([
                'status', 
                'payment_status', 
                'search',
                'date_from',
                'date_to',
                'amount_min',
                'amount_max'
            ])
        ]);
    }

    /**
     * 显示订单详情
     */
    public function show(Order $order)
    {
        $order->load([
            'user',
            'items.product.images',
            'items.variant.images',
            'userCoupon.coupon', // 加载优惠券信息
            'payments' => function($query) {
                $query->orderBy('created_at', 'desc');
            },
            'afterSalesRequests' => function($query) {
                $query->orderBy('created_at', 'desc');
            }
        ]);

        return Inertia::render('Admin/Orders/Show', [
            'order' => $order
        ]);
    }

    /**
     * 更新订单状态
     */
    public function updateStatus(Request $request, Order $order)
    {
        $request->validate([
            'status' => 'required|in:pending,processing,shipped,delivered,cancelled',
            'cancel_reason' => 'required_if:status,cancelled|nullable|string|max:500',
        ], [
            'status.required' => '请选择订单状态',
            'status.in' => '订单状态无效',
            'cancel_reason.required_if' => '取消订单时必须填写取消原因',
        ]);

        try {
            $oldStatus = $order->status;
            
            switch ($request->status) {
                case Order::STATUS_PENDING:
                    // 不允许回退到待支付状态
                    if (in_array($oldStatus, [Order::STATUS_PROCESSING, Order::STATUS_SHIPPED, Order::STATUS_DELIVERED])) {
                        return back()->with('error', '订单状态不允许回退到待支付');
                    }
                    $order->update(['status' => Order::STATUS_PENDING]);
                    break;

                case Order::STATUS_PROCESSING:
                    // 只允许从待支付进入处理中
                    if ($oldStatus === Order::STATUS_CANCELLED) {
                        return back()->with('error', '已取消的订单无法更改状态');
                    }
                    if ($oldStatus === Order::STATUS_DELIVERED) {
                        return back()->with('error', '已送达的订单无法更改状态');
                    }
                    $order->update(['status' => Order::STATUS_PROCESSING]);
                    break;

                case Order::STATUS_SHIPPED:
                    // 只允许从处理中进入已发货
                    if (!in_array($oldStatus, [Order::STATUS_PROCESSING, Order::STATUS_SHIPPED])) {
                        return back()->with('error', '只有待发货的订单可以标记为已发货');
                    }
                    $order->markAsShipped();
                    break;

                case Order::STATUS_DELIVERED:
                    // 只允许从已发货进入已送达
                    if ($oldStatus !== Order::STATUS_SHIPPED) {
                        return back()->with('error', '只有已发货的订单可以标记为已送达');
                    }
                    $order->markAsDelivered();
                    break;

                case Order::STATUS_CANCELLED:
                    // 不允许已送达的订单取消
                    if ($oldStatus === Order::STATUS_DELIVERED) {
                        return back()->with('error', '已送达的订单无法取消');
                    }
                    $order->cancel($request->cancel_reason ?? '管理员取消订单');
                    break;

                default:
                    $order->update(['status' => $request->status]);
            }

            // 记录日志
            $statusNames = [
                'pending' => '待支付',
                'processing' => '处理中',
                'shipped' => '已发货',
                'delivered' => '已送达',
                'cancelled' => '已取消',
            ];
            $this->logOrderStatusChange(
                orderNumber: $order->order_number,
                oldStatus: $statusNames[$oldStatus] ?? $oldStatus,
                newStatus: $statusNames[$request->status] ?? $request->status,
                model: $order
            );

            return back()->with('success', '订单状态更新成功');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * 标记订单为已支付
     */
    public function markAsPaid(Order $order)
    {
        if (!$order->canPay()) {
            return redirect()->back()->with('error', '订单状态不允许标记为已支付');
        }

        $order->markAsPaid();

        // 记录日志
        $this->logActivity(
            action: 'update',
            module: 'orders',
            description: "标记订单为已支付: {$order->order_number}",
            model: $order
        );

        return redirect()->back()->with('success', '已标记为已支付');
    }

    /**
     * 发货
     */
    public function ship(Request $request, Order $order)
    {
        $request->validate([
            'tracking_number' => 'nullable|string|max:255',
            'shipping_company' => 'nullable|string|max:255',
            'shipping_note' => 'nullable|string|max:1000',
        ], [
            'tracking_number.max' => '物流单号不能超过255个字符',
            'shipping_company.max' => '物流公司名称不能超过255个字符',
            'shipping_note.max' => '发货备注不能超过1000个字符',
        ]);

        try {
            $shippingData = [
                'tracking_number' => $request->tracking_number,
                'shipping_company' => $request->shipping_company,
                'shipping_note' => $request->shipping_note,
            ];

            $order->markAsShipped($shippingData);

            // 记录日志
            $this->logActivity(
                action: 'update',
                module: 'orders',
                description: "订单发货: {$order->order_number}，物流公司: {$request->shipping_company}，单号: {$request->tracking_number}",
                model: $order
            );

            return redirect()->back()->with('success', '发货成功');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 取消订单
     */
    public function cancel(Request $request, Order $order)
    {
        $request->validate([
            'reason' => 'required|string|max:500',
        ]);

        try {
            $order->cancel($request->reason);

            return redirect()->back()->with('success', '订单已取消，库存已恢复');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 批量标记为已支付
     */
    public function batchMarkAsPaid(Request $request)
    {
        $request->validate([
            'order_ids' => 'required|array|min:1',
            'order_ids.*' => 'integer|exists:orders,id',
        ]);

        try {
            $orders = Order::whereIn('id', $request->order_ids)
                ->where('payment_status', 'pending')
                ->get();

            $count = 0;
            foreach ($orders as $order) {
                if ($order->canPay()) {
                    $order->markAsPaid();
                    $count++;
                }
            }

            // 记录日志
            $this->logActivity(
                action: 'batch_update',
                module: 'orders',
                description: "批量标记 {$count} 个订单为已支付",
                model: null
            );

            return redirect()->back()->with('success', "成功标记 {$count} 个订单为已支付");

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 批量发货
     */
    public function batchShip(Request $request)
    {
        $request->validate([
            'order_ids' => 'required|array|min:1',
            'order_ids.*' => 'integer|exists:orders,id',
            'tracking_number' => 'nullable|string|max:255',
            'shipping_company' => 'nullable|string|max:255',
            'shipping_note' => 'nullable|string|max:1000',
        ]);

        try {
            $orders = Order::whereIn('id', $request->order_ids)
                ->where('status', 'processing')
                ->where('payment_status', 'paid')
                ->get();

            $shippingData = [
                'tracking_number' => $request->tracking_number,
                'shipping_company' => $request->shipping_company,
                'shipping_note' => $request->shipping_note,
            ];

            $count = 0;
            foreach ($orders as $order) {
                $order->markAsShipped($shippingData);
                $count++;
            }

            // 记录日志
            $this->logActivity(
                action: 'batch_update',
                module: 'orders',
                description: "批量发货 {$count} 个订单，物流公司: {$request->shipping_company}",
                model: null
            );

            return redirect()->back()->with('success', "成功发货 {$count} 个订单");

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 批量取消订单
     */
    public function batchCancel(Request $request)
    {
        $request->validate([
            'order_ids' => 'required|array|min:1',
            'order_ids.*' => 'integer|exists:orders,id',
            'reason' => 'required|string|max:500',
        ]);

        try {
            $orders = Order::whereIn('id', $request->order_ids)
                ->whereIn('status', ['pending', 'processing'])
                ->get();

            $count = 0;
            foreach ($orders as $order) {
                $order->cancel($request->reason);
                $count++;
            }

            // 记录日志
            $this->logActivity(
                action: 'batch_update',
                module: 'orders',
                description: "批量取消 {$count} 个订单",
                model: null
            );

            return redirect()->back()->with('success', "成功取消 {$count} 个订单");

        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
